﻿var page = new lg.page({
    data: {
        powerItem: "Read,Add,Edit,Delete",
        powerMap: {Read:"查看",Add:"添加",Edit:"编辑",Delete:"删除",Export:"导出",Import:"导入",backup:"备份"},
        module: [],
        class: [],
        grades: null
    },
    mounted: function () {
        this.InitEvent();
        this.List();
        this.GetModule();
        this.GetClass();
    },
    methods: {
        RenderGrades: function (success) {
            if (this.grades == null) {
                lg.request({
                    url: "/SysApi/GetGradesByDepth",
                    data: { depth: 1, fid: 0 },
                    success: res => {
                        if (res.code == 0) {
                            this.grades = res.data;
                            if (typeof success == "function") {
                                success(this.grades);
                            }
                        }
                    }
                })
            } else {
                if (typeof success == "function") {
                    success(this.grades);
                }
            }
        },
        InitEvent: function () {
            $("body").on("click", ".tree-drop-down", function () {
                $(this).siblings(".lg-diy-tree-level").toggle();
                $(this).toggleClass("fa-plus-square fa-minus-square");
            });
            $("body").on("click", ".layui-form-switch", function () {
                $(this).toggleClass("layui-form-onswitch");
            });
            $("body").on("click", ".layui-form-switch-all", function () {

            });
        },
        GetModule: function (func) {
            var that = this;
            lg.request({
                url: "/SysApi/GetSysModules",
                success: function (d) {
                    if (d.code == 0) {
                        that.module = d.data;
                    }                  
                }
            })
        },
        GetClass: function () {
            var that = this;
            lg.request({
                url: "/SysApi/GetClasses",
                success: function (d) {
                    if (d.code == 0) {
                        that.class = d.data;
                    }
                }
            })
        },
        GetTreeStr: function (id,data,key,type) { //id:FatherId,data:classIfy源数据，key:模块标题要显示的字段名,type:权限类型，1为系统模块 2为栏目分类
            var that = this;
            var html = "";
            var obj = data.filter(p => p.FatherId == id);
            if (obj.length > 0) {
                for (let i in obj) {
                    var m = obj[i];
                    var sub = data.filter(p => p.FatherId == m.Id);
                    html += "<div class='lg-diy-tree-level lg-diy-tree-level-"+m.Depth+"'>";
                    if (sub.length > 0) {
                        html += "<div class='tree-drop-down fa fa-plus-square'></div>"
                    }
                    html += "<div class='tree-box' data-id='"+m.Id+"' data-type='"+type+"'><span class='tree-name'>" + m[key] + "</span>";
                    var powerItem=["Read","Add","Edit","Delete"]
                    if (m.PowerItem) {
                        powerItem = m.PowerItem.split(",");
                    }
                    for (let s in powerItem) {
                        let field = powerItem[s]
                        html += "<div class='layui-unselect layui-form-switch item' data-power='" + field + "'><em>" + this.powerMap[field] + "</em><i></i></div>";
                    }
                    html += "</div>";
                    if (sub.length > 0) {
                        html += that.GetTreeStr(m.Id, data, key,type);
                    }
                    html += "</div>"
                }
            }
            return html;
        },
        InitPowerItems: function () {
            if (this.module) {
                let moduleTree = this.GetTreeStr(0, this.module, "Name", 1);
                $("#module-tree").html(moduleTree);
            }
            if (this.class) {
                let classTree = this.GetTreeStr(0, this.class, "ClassName", 2);
                $("#class-tree").html(classTree);
            }
        },
        GetPowers: function () {
            var data = [];
            $(".tree-box").each(function () {
                var item = $(this).find(".item.layui-form-onswitch");
                if (item.length > 0) {
                    let obj = {};
                    obj.Id = $(this).data("id");
                    obj.Type = $(this).data("type");
                    let arr = [];
                    item.each(function () {
                        arr.push($(this).data("power"))
                    })
                    obj.Powers = arr.join(",")
                    data.push(obj);
                }  
            })
            if (data.length > 0) {
                return JSON.stringify(data);
            } else {
                return "";
            }
            
        },
        PowerRender: function (data) {
            $(".tree-box").each(function () {
                let id = $(this).data("id");
                let type = $(this).data("type");
                let arr = data.filter(p => p.Id == id && p.Type == type);
                if (arr.length > 0) {
                    let obj = arr[0];
                    let powers = obj.Powers.split(",");
                    if (powers.length > 0) {
                        let tree = $(this).find(".item");
                        tree.each(function () {
                            let key = $(this).data("power");
                            if (powers.indexOf(key) >= 0) {
                                $(this).addClass("layui-form-onswitch");
                            }
                        })
                    }
                }

            })
        },
        List: function () {
            layui.use(['table', 'element', 'form'], function () {
                var table = layui.table;
                var form = layui.form;
                var element = layui.element  //元素
                page.laytable = table.render({
                    elem: '#RoleList'
                    , url: '/SysApi/GetRoles'
                    , toolbar: '#toolbar' //开启头部工具栏，并为其绑定左侧模板
                    , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    , cols: [[
                        {
                            field: 'rownum', title: '#', width: 80, templet: function (d) {
                                return d.LAY_TABLE_INDEX + 1
                            }
                        }
                        , {
                            field: 'RoleName', title: '角色名称',
                        }
                        , {
                            field: 'RoleIntro', title: '角色描述',
                        }
                        , {
                            field: 'IsUsing', title: '是否启用', width: 100, align: "center", templet: function (d) {
                                return laySwitch.render(d.IsUsing,"use");
                            }
                        }

                        , { fixed: 'right', title: '操作', toolbar: '#btTpl', }
                    ]],
                });
                //头工具栏事件
                table.on('toolbar(RoleList)', function (obj) {
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch (obj.event) {
                        case 'addRole':
                            loadTpl({
                                url: "/Lgm/AddRole",
                                target: "#floatBody"
                            })
                            return false;
                            break;
                        case 'refresh':
                            page.laytable.reload();
                            break;
                    };
                });
                //监听行工具事件
                table.on('tool(RoleList)', function (obj) {
                    var data = obj.data;
                    //console.log(obj)
                    switch (obj.event) {
                        case 'del':
                            layer.confirm('真的删除行么', function (index) {
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        case 'edit':
                            loadTpl({
                                url: "/Lgm/EditRole/" + data.Id,
                                target: "#floatBody"
                            })
                            break
                        case 'use':
                            data.IsUsing = data.IsUsing == 1 ? 0 : 1;
                            lg.request({
                                url: "/SysApi/EditRole",
                                method: "post",
                                data: { Id: data.Id, IsUsing: data.IsUsing },
                                success: function (d) {
                                    if (d.code == 0) {
                                        obj.update(data);
                                        layer.msg("操作成功!", { icon: 1 });
                                    } else {
                                        layer.msg(d.msg, { icon: 2 })
                                    }
                                }
                            });
                            break;
                    }

                });

            });
        },
        Add: function () {
            var form = layui.form;
            this.InitPowerItems();
            var form = layui.form;
            form.render();
            var that = this;
            this.RenderGrades(res => {
                lg.select.fill({
                    data: res,
                    target: "#GradeId",
                    value: "Id",
                    text: "GradeName",
                    callback: function () {
                        form.render();
                    }
                })
            })
            form.on("submit(RoleAdd)", function (data) {
                var d = data.field;
                d.Powers = that.GetPowers();
                lg.request({
                    url: "/SysApi/AddRole",
                    method: "post",
                    data: d,
                    success: function (d) {
                        if (d.code == 0) {
                            layer.msg("添加成功!", { icon: 1 });
                            page.back(true);
                        } else {
                            layer.msg(d.msg, {icon:2})
                        }
                    }
                })
                return false;
            })
        },
        Edit: function (id) {
            var that = this;
            var form = layui.form;
            this.InitPowerItems();
            form.render();
            this.RenderGrades(res => {
                lg.select.fill({
                    data: res,
                    target: "#GradeId",
                    value: "Id",
                    text: "GradeName",
                    callback: function () {
                        form.render();
                        lg.request({
                            url: "/SysApi/GetRole/" + id,
                            success: function (d) {
                                if (d.code == 0) {
                                    form.val("fm-roleEdit", d.data);
                                    if (d.data.Powers) {
                                        that.PowerRender(JSON.parse(d.data.Powers))
                                    }
                                }
                            }
                        })  
                    }
                })
            })  
            form.on("submit(RoleEdit)", function (data) {
                var d = data.field;
                d.Id = id;
                d.Powers = that.GetPowers();
                lg.request({
                    url: "/SysApi/EditRole",
                    method: "post",
                    data: d,
                    success: function (d) {
                        if (d.code == 0) {
                            layer.msg("编辑成功!", { icon: 1 });
                            page.back(true);
                        } else {
                            layer.msg(d.msg, { icon: 2 })
                        }
                    }
                })
                return false;
            })
        }
    }
})